import 'package:flutter/material.dart';

import 'package:drm/login/bloc.dart';
import 'package:drm/base/user.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'bloc.dart';
import 'package:drm/util/loading_dialog.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'package:drm/other_bloc/to_ipSetting_page.dart';
import 'package:drm/resource/string_resource.dart';
import 'package:drm/util/utils.dart';



class LoginPage extends StatefulWidget {
  BuildContext _context;

  LoginPage(this._context, {Key key, this.title}) : super(key: key);
  final String title;

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage>  {
  bool _isObscure = true;
  Color _eyeColor = Colors.grey;

  //是否显示网络进度栏
  Widget progressBar = WidgetCreator.createCommonProgressBar();
  bool showProgress = false;
  String nameError;
  String passwordError;
  bool isSaveUser = false;


  TextEditingController _userNameControl = TextEditingController();
  TextEditingController _passwordControl = TextEditingController();


  LoginBloc loginBloc = LoginBloc();
  ToIpSettingBloc _toIpSettingBloc = ToIpSettingBloc();

 int flag = 0 ;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loginBloc.dispatch(LoadLoaclUser());
//
//    MyUtils.getNowAppVerCode().then((String version) {
//      print(version);
//    });
//     User localUser  = SpUtils.getLocalUser();
//     if (localUser != null) {
//       _userNameControl.text = localUser.loginName;
//       _passwordControl.text = localUser.password;
//       isSaveUser = localUser.isSave;
//     }

  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _userNameControl.dispose();
    _passwordControl.dispose();
    loginBloc.dispose();
    _toIpSettingBloc.dispose();
    Fluttertoast.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder(
        bloc: loginBloc,
        builder: (context, loginState) {
          if (loginState is LoginLoading) {
            showProgressBar();
          }
          if (loginState is LoginLoadingHide) {
            hideProgressBar();
          }
          if (loginState is LoginSuccess) {

             hideProgressBar();

            if (loginState.loginResultEntity.isSuccess) {
              loginBloc.dispatch(LoginSaveUserEvent(User(
                loginName: _userNameControl.text,
                password: _passwordControl.text,
                isSave: isSaveUser,
                dlsId: loginState.loginResultEntity.dlsId,
                dlsTopId: loginState.loginResultEntity.dlsTopId,
                userId: loginState.loginResultEntity.userId,
                fwsId: loginState.loginResultEntity.fwsId,
              )));
            }else {
              showToast(loginState.loginResultEntity.info);
              //避免下次刷新页面的时候，跳出 toast ；
              loginBloc.dispatch(NullLoginEvent());
            }
          }
          if (loginState is LoadLoaclUserState) {
            if (loginState.user != null) {
              if (loginState.user.isSave) {
                _userNameControl.text = loginState.user.loginName;
                _passwordControl.text = loginState.user.password;
                isSaveUser = loginState.user.isSave;
              }
            }
            loginBloc.dispatch(NullLoginEvent());
          }

          if (loginState is LoginPassWordEditState) {
            _isObscure = loginState.isShow;
            _eyeColor =
                _isObscure ? Colors.grey : Theme.of(context).primaryColor;
          }

          if (loginState is LoginUserNameEditChanagedState) {
            _passwordControl.text = '';
            loginBloc.dispatch(NullLoginEvent());
          }

          if (loginState is LoginCheckState) {
            passwordError = loginState.passwordError;
          }

          if (loginState is LoginSaveUserChangedState) {
            isSaveUser = loginState.isSaveUser;
          }
          if (loginState is NullLoginEventState) {
            print('接收到了空状态state');
          }

          return Stack(children: <Widget>[
            homePage(context,loginState),
            Offstage(
              child: new Center(
                child: progressBar,
              ),
              offstage: !showProgress,
            ),
          ]);
        });
  }

//  Widget testPage(LoginState loginState) {
//    return Material(
//      child: Container(
//        padding: EdgeInsets.only(left: 50, right: 50),
//        child: Column(
//          mainAxisAlignment: MainAxisAlignment.center,
//          children: <Widget>[
//            Expanded(
//              child: Column(
//                mainAxisAlignment: MainAxisAlignment.center,
//                children: <Widget>[
//                  buildLogImage(),
//                  buildUserNameTextField(loginState, context),
//                  paddingView(10),
//                  buildPasswordTextField(loginState, context),
//                  paddingView(15),
//                  buildForgetPasswordText(loginState, context),
//                  paddingView(6),
//                  buildLoginButton(loginState, context),
//                  buildSettingText(context),
//                ],
//              ),
//            ),
//            buildBqText(context)
//          ],
//        ),
//      ),
//
//    );
//  }

  Widget homePage(BuildContext context,LoginState loginState) {
    return  Material(
      child: Container(
        padding: EdgeInsets.only(left: 50, right: 50),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  buildLogImage(),
                  buildUserNameTextField(loginState, context),
                  paddingView(10),
                  buildPasswordTextField(loginState, context),
                  paddingView(15),
                  buildForgetPasswordText(loginState, context),
                  paddingView(6),
                  buildLoginButton(loginState, context),
                  buildSettingText(context),
                ],
              ),
            ),
            buildBqText(context)
          ],
        ),
      ),
    );
  }

  Widget buildLogImage() {
    return Container(
      height: 100,
      width: 100,
      margin: EdgeInsets.only(bottom: 60),
      child: Image.asset(
        'images/zxlogo.png',
        fit: BoxFit.cover,
      ),
    );
  }

  Widget buildUserNameTextField(LoginState loginState, BuildContext context) {
    return TextField(

      controller: _userNameControl,

      decoration: InputDecoration(
          hintText: '用户名', prefixIcon: Icon(Icons.face), errorText: nameError),
      maxLength: 20,
      onChanged: (value) {
        if (value.isNotEmpty) {
          loginBloc.dispatch(LoginUserNameEditChanagedEvent());
        }
      }

    );
  }

  Widget buildPasswordTextField(LoginState loginState, BuildContext context) {
    return TextField(
      obscureText: _isObscure,
      controller: _passwordControl,
      maxLength: 20,
      decoration: InputDecoration(
          hintText: '密码',
          errorText: passwordError,
          prefixIcon: Icon(Icons.https),
//          suffixIcon: IconButton(
//              icon: Icon(
//                Icons.remove_red_eye,
//                color: _eyeColor,
//              ),
//              onPressed: () {
//                loginBloc.dispatch(LoginPassWordEditEvent(_isObscure));
//              })


      ),
    );
  }

  Widget buildForgetPasswordText(LoginState loginState, BuildContext context) {
    return Row(
      children: <Widget>[
        Checkbox(
            value: isSaveUser,
            activeColor: Theme.of(context).primaryColor,
            onChanged: (value) {
              loginBloc.dispatch(LoginSaveUserChangedEvent(value));
            }),
        Expanded(
          child: Text('记住密码'),
          flex: 1,
        ),
//        FlatButton(
//          child: Text(
//            '忘记密码？',
//            style: TextStyle(
//                fontSize: 14.0, color: Theme.of(context).primaryColor),
//          ),
//          onPressed: () {
//            Navigator.pop(context);
//          },
//        )
      ],
    );
  }

  Widget buildLoginButton(LoginState loginState, BuildContext context) {
    return BlocListener(
        bloc: loginBloc,
        listener: (context, loginState) {
          if (loginState is LoginSaveUserEventState) {
            if (loginState.isSaveSuccess) {
              //跳转主界面；
              _goMain();
            } else {
              showToast('本地数据保存失败，无法登录');
            }
          }
          if (loginState is LoginCheckState) {
            nameError = loginState.nameError;
          }
        },
        child: Align(
          child: SizedBox(
            height: 45.0,
            width: 300.0,
            child: RaisedButton(
              child: Text(
                '登录',
                style: TextStyle(
                    color: Colors.white, letterSpacing: 10, fontSize: 20),
              ),
              color: Theme.of(context).primaryColor,
              onPressed: () {
                login();
              },
              shape: StadiumBorder(
                  side: BorderSide(color: Theme.of(context).primaryColor)),
            ),
          ),
        ));

  }

  Widget paddingView(double size) {
    return SizedBox(
      height: size,
    );

  }

  Widget buildSettingText(BuildContext context) {
    return BlocListener(
        bloc: _toIpSettingBloc,
        listener: (context, state) {
          if( state is ToIpSettingState && state.isShow) {
            _goIpSetting();
          }
        },
        child: Padding(
          padding: const EdgeInsets.only(top: 8.0),
          child: Align(
            alignment: Alignment.center,
            child: FlatButton(
              child: Text(
                '服务器设置',
                style: TextStyle(
                    fontSize: 14.0, color: Theme.of(context).primaryColor),
              ),
              onPressed: () {
                _toIpSettingBloc.dispatch(ToIpSettingEvent());
              },
            ),
          ),
        ));

  }

  Widget buildBqText(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 8.0, bottom: 20),
      child: Align(
        alignment: Alignment.bottomCenter,
        child: Text('${StringRes.banben}')
      ),
    );
  }

  login() {
    flag = 0 ;
    LoginCheckEvent loginCheckEvent = LoginCheckEvent(
        User(loginName: _userNameControl.text, password: _passwordControl.text),
        nameError,
        passwordError);
    if (loginCheckEvent.check()) {
      nameError = null;
      passwordError = null ;

      loginBloc.dispatch(Login(User(
          loginName: _userNameControl.text, password: _passwordControl.text)));
    } else {
      loginBloc.dispatch(loginCheckEvent);
    }
  }

  showToast(String msg) {
    Fluttertoast.showToast(
        msg: msg,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Colors.black45,
        textColor: Colors.white,
        fontSize: 16.0);
  }

  /*
   * 显示网络进度栏及关闭软键盘<br/>
   */
  void showProgressBar({String text}) {
    showProgress = true;
  }

  /*
   * 隐藏并重置网络进度栏<br/>
   */
  void hideProgressBar() {
    showProgress = false;
  }

  void _goMain() {
    Navigator.pushNamed(widget._context, 'mainPage');
  }

  void _goIpSetting() {
    Navigator.pushNamed(widget._context, 'ipSetting');
  }
}
